package com.ruoyi.common;/*
 *
 * 2021-12-03 17:15
 */

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

@Slf4j
public class FileOSSUtil {
    private static String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    private static String ACCESS_KEY_ID = "LTAI5tCqeaGiHYeSZLRWwK9q";
    private static String ACCESS_KEY_SECRET = "19buIpTe58juqIFmhFdbtR5RqNyJpj";
    private static String BUCKETNAME = "dgw-mubiao";
    private static String SUFFER_URL = "http://dgw-mubiao.oss-cn-beijing.aliyuncs.com/";
    private static String NAME ="wuhaihua";
    /*
     * 获取OSS连接
     * */
    public OSS getOSSClient() {

        /*创建一个OSSClient对象*/
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        //判断仓库是否存在
        if (ossClient.doesBucketExist(BUCKETNAME)) {
            log.info("bucket存在");
        } else {
            //通过api接口方式创建bucket仓库
            log.info("bucket不存在：{}", BUCKETNAME);
            CreateBucketRequest buildBucketRequest = new CreateBucketRequest(null);
            buildBucketRequest.setBucketName(BUCKETNAME);
            buildBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(buildBucketRequest);
            //   ossClient.shutdown();
        }

        return ossClient;
    }

    public String uploadDocument(MultipartFile multipartFile) throws IOException {
        //连接oss
        OSS ossClient = this.getOSSClient();
        //获取后缀名
        String ext = multipartFile.getOriginalFilename();
        ext = ext.substring(ext.lastIndexOf("."));
        String date = DateUtils.getDate();
        String uuid = RandomUtil.randomUUID(32).replace("-","");
        String fileName= NAME+"/"+date+"/"+ uuid+ext;
        ossClient.putObject(BUCKETNAME,fileName,new ByteArrayInputStream(multipartFile.getBytes()));
        String url = SUFFER_URL+fileName;
        ossClient.shutdown();
        return url;
    }


}
